import logging
from datetime import datetime

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class MaintenanceState(models.Model):
    _name = "maintenance.state"

    name = fields.Char(string='设备名称')
    work_start_time = fields.Datetime(string='开始工作时间')
    work_duration_time = fields.Char(
        string='工作持续时间', 
        compute='_compute_time', 
        readonly=True
        )
    state = fields.Selection(
        string='状态', 
        selection=[('normal', '正常'), ('halt', '停机'), ('maintain', '维修中')], 
        default='normal'
        )

    # 计算工作持续时间
    @api.depends('work_start_time')
    def _compute_time(self):
        for r in self:
            if r.work_start_time:
                time_delta = datetime.now() - fields.Datetime.from_string(r.work_start_time)
                if time_delta.days:
                    r.work_duration_time = '{}天{:.0f}小时{:.0f}分'.format(time_delta.days, time_delta.seconds / 60 // 60,
                                                             time_delta.seconds / 60 % 60)
                else:
                    r.work_duration_time = '{:.0f}小时{:.0f}分'.format(time_delta.seconds / 60 // 60, time_delta.seconds / 60 % 60)